from __future__ import annotations

from typing import Any, List

import gdb  # type: ignore

from .base import Adapter
from .utils import value_to_python


class StdVectorAdapter(Adapter):
    name = "stl_vector"

    def supports(self, gdb_value: gdb.Value) -> bool:
        try:
            typename = gdb_value.type.strip_typedefs().name or ""
            return "std::vector" in typename
        except Exception:
            return False

    def serialize(self, gdb_value: gdb.Value) -> Any:
        result: List[Any] = []

        # 1) 优先使用 libstdc++ pretty-printer（gdb.default_visualizer）
        printer = gdb.default_visualizer(gdb_value)
        if printer is not None:
            try:
                for _name, child in printer.children():
                    result.append(value_to_python(child))
                return result
            except Exception:
                # 如果 pretty-printer 存在但遍历失败，回退到手动方式
                pass

        # 2) 手动解析 std::vector 布局：_M_impl._M_start/_M_finish
        try:
            impl = gdb_value["_M_impl"]
            start = impl["_M_start"]
            finish = impl["_M_finish"]
            length = int(finish - start)

            element_type = gdb_value.type.template_argument(0)
            ptr = start

            for _ in range(length):
                result.append(value_to_python(ptr.dereference()))
                ptr = ptr + 1

            return result
        except Exception as exc:
            return {"__error__": str(exc)}